import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:riverpod_t/routers/navigator_utils.dart' show NavigatorUtils;
import 'package:riverpod_t/widget/easy_loading.dart';
import 'base_will_pop.dart';

abstract class BasePage extends StatefulWidget {
  const BasePage({super.key});

  @override
  BasePageState createState() => getState();

  /// 子类必须实现的获取状态方法
  BasePageState getState();
}

abstract class BasePageState<T extends BasePage> extends State<T> {
  /// 页面渲染控制
  bool _shouldRenderPage = false;

  /// 导航栏相关属性
  bool showAppBar = true;
  Color? appBarColor;
  String appBarTitle = '';
  bool allowBackNavigation = true;

  /// 布局相关属性
  EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 14.w, vertical: 14.h);
  Color pageBackgroundColor = const Color(0xFFF9FAFB);
  bool adjustForKeyboard = true;

  /// 尺寸信息
  late double appBarHeight;
  late double statusBarHeight;
  late double bottomSafeAreaHeight;

  @override
  void initState() {
    super.initState();
    _initializeDimensions();
    _addPostFrameCallback();
    _logCurrentPage();
  }

  @override
  void dispose() {
    XsEasyLoading.dismiss();
    super.dispose();
  }

  /// 初始化屏幕尺寸信息
  void _initializeDimensions() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      statusBarHeight = ScreenUtil().statusBarHeight;
      bottomSafeAreaHeight = ScreenUtil().bottomBarHeight;
      appBarHeight = AppBar().preferredSize.height;

      setState(() => _shouldRenderPage = true);
    });
  }

  /// 添加帧回调
  void _addPostFrameCallback() {
    WidgetsBinding.instance.addPostFrameCallback((_) => onBuildComplete());
  }

  /// 记录当前页面
  void _logCurrentPage() {
    debugPrint('当前页面: $runtimeType');
  }

  /// 构建完成后回调
  void onBuildComplete() {}

  /// 处理返回操作
  void handleBackAction() {
    if (!allowBackNavigation) return;
    NavigatorUtils.unFocus();
    NavigatorUtils.pop(context);
  }

  /// 左侧导航栏按钮
  Widget buildLeftButton() {
    return GestureDetector(
      onTap: handleBackAction,
      child: Container(padding: buttonPadding, child: _defaultBackButton()),
    );
  }

  /// 默认返回按钮
  Widget _defaultBackButton() {
    return Image.asset("assets/images/back_black.png", height: 20.h, width: 20.w);
  }

  /// 右侧导航栏按钮
  Widget buildRightButton() {
    return Container(padding: buttonPadding, child: const SizedBox(width: 20));
  }

  /// 页面主要内容
  Widget buildPageContent() {
    return Container(
      color: pageBackgroundColor,
      height: double.infinity,
      width: double.infinity,
      child: buildPage(context),
    );
  }

  /// 子类必须实现的页面构建方法
  Widget buildPage(BuildContext context);

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: WillPopScope(
        onWillPop: () async => allowBackNavigation,
        child: Scaffold(
          appBar: showAppBar ? _buildAppBar() : null,
          body: _shouldRenderPage ? buildPageContent() : _buildLoadingPlaceholder(),
          resizeToAvoidBottomInset: adjustForKeyboard,
        ),
      ),
    );
  }

  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      centerTitle: true,
      title: Text(
        appBarTitle,
        style: TextStyle(color: Colors.black, fontSize: 17.sp, fontWeight: FontWeight.w500),
      ),
      leading: buildLeftButton(),
      elevation: 0.2,
      actions: [buildRightButton()],
      backgroundColor: appBarColor ?? Colors.white,
    );
  }

  /// 构建加载占位符
  Widget _buildLoadingPlaceholder() {
    return const Center(child: CircularProgressIndicator());
  }
}
